package adminlte.vo;

import adminlte.model.Menu;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZHUFEIFEI
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MenuVo extends Menu{
    private List<Menu> children;

    public MenuVo(Menu m) {
        this.setId(m.getId());
        this.setPid(m.getPid());
        this.setText(m.getText());
        this.setUrl(m.getUrl());
    }

    public void add(MenuVo m) {
        if (this.getChildren() == null) {
            this.setChildren(new ArrayList<>());
        }
        this.getChildren().add(m);
    }

    @JsonIgnore
    @Override
    public Long getPid() {
        return super.getPid();
    }

    public static List<MenuVo> convert(List<Menu> menus) {
        Map<Long, MenuVo> maps = new HashMap<>(menus.size());
        menus.forEach(m -> maps.put(m.getId(), new MenuVo(m)));
        Map<Long, MenuVo> result = new HashMap<>(maps.size());
        for (Map.Entry<Long, MenuVo> kv : maps.entrySet()) {
            if (kv.getValue().getPid() == null || kv.getValue().getPid() <= 0) {
                result.put(kv.getKey(), kv.getValue());
            } else {
                maps.get(kv.getValue().getPid()).add(kv.getValue());
            }
        }
        return new ArrayList<>(result.values());
    }
}
